package indi.defoliation.unknownrpg.api.config;

import java.io.File;
import java.io.IOException;

import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;

import com.google.common.io.Files;

import team.unstudio.udpl.config.AutoCharsetYamlConfiguration;

public class YamlConfigurer implements Configurer {
	
	private File file;
	private YamlConfiguration config;
	
	public YamlConfigurer(JavaPlugin plugin,String fileName) {
		file = new File(plugin.getDataFolder(),fileName);
		reload();
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T get(String key) {
		try {
			return (T)config.get(key);
		}catch(Exception e) {
			return null;
		}
	}
	
	public void set(String key,Object value) {
		config.set(key, value);
	}
	
	public boolean contains(String key) {
		return config.contains(key);
	}

	@Override
	public void reload() {
		touch();
		config = AutoCharsetYamlConfiguration.loadConfiguration(file); 
	}

	@Override
	public void save() {
		touch();
		try {
			config.save(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void touch() {
		try {
			Files.touch(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
